<template>
    <div>
        <el-card style="height: 85px">
            <div style="display: flex;margin: 0 auto;position: relative"><h1>写文章</h1>
                <div style="position: absolute;right: 300px">
                    <el-button @click="publish">发布</el-button>
                    <!--                    <el-button @click="add">新增</el-button>-->
                    <el-button>取消</el-button>
                    <el-button type="primary" @click="back()">返回</el-button>
                </div>
            </div>
        </el-card>
        <!--        富文本-->
        <el-dialog

                title="介绍、分类、标签"
                :visible.sync="dialogVisible"
                width="48%"
                :before-close="handleClose">
            <el-form :model="form" :rules="rules" ref="formRef" class="demo-ruleForm">
                <!--                标题-->
                <el-form-item label="标题" prop="title">
                    <el-input
                            type="input"
                            :rows="10"
                            placeholder="请输入内容"
                            v-model="form.title">
                    </el-input>
                </el-form-item>

                <!--                介绍-->
                <el-form-item label="介绍" prop="description">
                    <el-input
                            type="input"
                            :rows="10"
                            placeholder="请输入内容"
                            v-model="form.description">
                    </el-input>
                </el-form-item>
                <!--                分类-->
                <el-form-item label="分类" prop="typeName">
                    <!--                    选择框，label表示展示的数据， value表示选中的值  这里的v-model表示选中的值绑定到这-->
                    <el-select v-model="form.typeId" placeholder="请选择活动区域">
                        <el-option v-for="item in type" :label="item.typeName" :value="item.typeId">{{item.typeName}}
                        </el-option>
                    </el-select>
                </el-form-item>
                <!--标签-->
                <el-form-item label="标签" prop="tagName">
                    <template>
                        <!--                        -->
                        <el-checkbox-group v-model="form.tagIds">  <!-- 这里表示选中的值绑定到这 -->>
                            <!--                            如果这个博客的标签id和遍历的标签id相同就选中-->
                            <el-checkbox :checked="form.tagIds[index]===item.tagId?checked:false"
                                         @change="changeValue(item)" :key="item.tagId"
                                         v-for="(item,index) in tag"
                                         :label="item.tagId"
                            >{{item.tagName}}
                            </el-checkbox>                             <!-- 中间用来展示数据 label表示选中的值-->

                        </el-checkbox-group>
                    </template>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose('formRef')">取 消</el-button>
            <el-button type="primary" @click="edit('formRef')">确 定</el-button>
          </span>
        </el-dialog>
        <!--        附加信息-->

        <div style="display: flex;justify-content: center;margin-top: 10px;height: 80vh">
            <div id="div1" style="width: 80%;height: 100vh;z-index: 1">
            </div>
        </div>

    </div>
</template>

<script>
    import E from 'wangeditor'
    // import jwtDecode from "jwt-decode";
    import jwtDecode from 'jwt-decode'
    import hljs from "highlight.js";

    // const editor = new E('#div1')
    let editor;  // 全局变量
    export default {
        name: "Edit",

        methods: {
            async getType() {   // 获取分类数据
                const {data: res} = await this.$http.get('/admin/type/addblog')
                // console.log(res)
                this.type = res.data;

            },
            async getTag() {  // 获取标签数据
                const {data: res} = await this.$http.get('/admin/tag/addblog')
                this.tag = res.data;
                // console.log(res)
                // console.log(this.tag);
            }
            ,
            publish() {  //  发布文章
                // console.log(111)
                // const editor = document.querySelector('#div1')
                var content = null;
                this.$nextTick(() => {
                    // console.log(editor.txt.html());

                    this.form.content = editor.txt.html();

                })
                console.log(this.form.content);
                this.dialogVisible = true;

                // console.log(html)
            },
            edit(formRef) { // 修改博客
                this.dialogVisible = true;
                // console.log(formAddRef);
                const token = localStorage.getItem('token')
                const obj = jwtDecode(token)

                let userId = obj.id;
                this.form.userId = userId;
                this.form.id = this.$route.query.id; // 确保博客id传到后端
                this.$refs[formRef].validate(async (valid) => { // 前端校验
                        if (valid) {

                            const {data: res} = await this.$http.put('/blog/platform/', this.form)
                            // console.log(res);
                            // this.$message.success('test')
                            if (res.meta.status === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '修改博客成功'
                                })
                                this.dialogVisible = false;
                                // this.form.tagIds = []; // 初始化
                                // this.form = {}; // 初始化
                                // editor.txt.clear() // 清空富文本的内容
                                if (obj.type === 1) {
                                    this.$router.push('/adminblog')

                                } else if (obj.type === 0) {
                                    this.$router.push('/platform')

                                }
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.meta.msg
                                })
                                this.dialogVisible = false;
                            }
                        } else {
                            this.$message({
                                type: 'error',
                                message: '请检查！'
                            })
                            return false;
                        }
                        // this.$message.error('222')
                    }
                );
                // this.dialogVisibleAdd = true;
                this.$refs[formRef].resetFields();
            },
            handleClose(formRef) { //对话框取消
                this.dialogVisible = false;
                this.$refs[formRef].resetFields();


            },
            back() { // 返回首页
                this.$router.go(-1)

            },
            changeValue(item) {
                console.log(item)
                // this.form.tagIds.push(item.tagId)
            },
            async getBlogInfo(id) {  // 回显数据
                const token = localStorage.getItem('token')
                const obj = jwtDecode(token)
                console.log(obj)
                const {data: res} = await this.$http.get('/admin/blog/' + id)
                // console.log(res);
                editor.txt.html(res.data.content) // 重新设置编辑器内容
                this.form.title = res.data.title;
                this.form.description = res.data.description;
                this.form.typeId = res.data.typeId;
                this.form.tagIds = res.data.tagsId;
                this.form.id = id;
            }
        },

        data() {
            return {
                checkList: ['选中且禁用', '复选框 A']
                ,
                dialogVisible: false, // 富文本,
                form: {
                    id: "",
                    content: "",
                    // content: "",
                    description: '',
                    title: '',
                    tagIds: [],
                    typeId: ""
                },
                type: [],
                tag: [],
                rules: { // 自定义规则
                    description: [
                        {required: true, message: '介绍不能为空', trigger: 'blur'},
                        // {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ], title: [
                        {required: true, message: '标题不能为空', trigger: 'blur'},
                        // {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ],
                    type: [
                        {required: true, message: '请选择活动区域', trigger: 'change'}
                    ],
                    tag: [
                        {type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change'}
                    ],
                }
            }
        }, created() {
            console.log(this.$route.query.id)
            this.getBlogInfo(this.$route.query.id)
            this.getType();
            this.getTag();
        },
        mounted() {
            editor = new E('#div1')
            editor.config.uploadFileName = 'file'
            editor.config.height = 1200
            editor.config.uploadVideoName = 'file'
            // 配置 server 接口地址
            editor.config.uploadVideoServer = 'http://localhost:8888/blog/uploadvideo'
            // 配置 server 接口地址
            editor.config.uploadImgServer = 'http://localhost:8888/blog/upload'
            // 挂载highlight插件
            editor.highlight = hljs
            // 配置颜色（文字颜色、背景色）
            editor.config.colors = [
                '#000000',
                '#eeece0',
                '#1c487f',
                '#4d80bf'
            ]
            // 配置字体
            editor.config.fontNames = [
                // 对象形式 v4.6.16
                {name: "黑体", value: "黑体"},
                {name: "绝绝字体", value: "Times New Roman"},
                // 字符串形式
                '黑体',
                '仿宋',
                '楷体',
                '标楷体',
                '华文仿宋',
                '华文楷体',
                '宋体',
                '微软雅黑',
                'Arial',
                'Tahoma',
                'Verdana',
                'Times New Roman',
                'Courier New',
            ]
            editor.create()
            // editor.config.uploadImgShowBase64 = true
        },
    }
</script>

<style lang="less" scoped>

</style>